package com.koo.modules.quartz.server.impl;

import cn.hutool.core.date.DateUtil;
import com.koo.common.utils.MyStrUtil;
import com.koo.framework.config.ThirdPropFileConfig;
import com.koo.modules.b2b.entity.B2bStoreEntity;
import com.koo.modules.b2b.service.B2bStoreService;
import com.koo.modules.quartz.constant.AdminConstant;
import com.koo.modules.quartz.constant.B2BConstant;
import com.koo.modules.quartz.constant.B2BTimeConstant;
import com.koo.modules.quartz.server.BaseThirdDataService;
import com.koo.modules.quartz.util.MysqlJDBCUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Slf4j
@Service
public class AdminStoreThirdDataServiceImpl implements BaseThirdDataService {

    private String[] COMPANY_PREFIXS = AdminConstant.ALL_COMPANY_PREFIXS.getPrefixDatas();

    @Autowired
    private B2bStoreService b2bStoreService;


    @Override
    public boolean checkNeedThirdData() {
        return "true".equals(ThirdPropFileConfig.getProperty("runSync_" + B2BConstant.ADMIN.getCompanyCode()));
    }


    @Override
    public void storeDataToAdminTransport() {
        if (!checkNeedThirdData()) {
            return;
        }
        //1.查询监控端门店最大同步时间, 根据时间查询每个前缀数据库的门店信息
        //2.查询监控端门店是否存在, 存在修改, 不存在新增
        Connection connection = null;
        String sql = "SELECT MAX(transport_time) as transportTime FROM sys_store;";
        Integer updateCount = 0, insertCount = 0;
        try {
            connection = MysqlJDBCUtil.setAutoCommitFalse(B2BConstant.ADMIN.getCompanyCode());
            ResultSet maxTransportDateRs1 = MysqlJDBCUtil.execQuery(sql, connection);
            Timestamp maxTransportDate = null;
            if (maxTransportDateRs1.next()) {
                maxTransportDate = maxTransportDateRs1.getTimestamp(1);
            }
            List<B2bStoreEntity> b2bStores = new ArrayList<>();
            //查询每个前缀数据库的门店信息
            for (String prefix : COMPANY_PREFIXS) {
                // 查询对应前缀的门店数据
                List<B2bStoreEntity> prefixStores = b2bStoreService.listStoreByPrefixAndTransportDate(prefix, maxTransportDate);
                b2bStores.addAll(prefixStores);
            }
            Iterator<B2bStoreEntity> iterator = b2bStores.iterator();
            StringBuilder insertValues = new StringBuilder();
            boolean needInsert = false;
            while (iterator.hasNext()) {
                B2bStoreEntity store = iterator.next();
                sql = "UPDATE sys_store SET company_id = ?, store_type = ?, store_code = ?, store_name = ?, store_full_name = ?, mobile = ?, contactor = ?, tel = ?, store_address = ?, status = ?, update_time = ?, remark = ?, transport_time = ? WHERE store_id = ? ;";
                // 更新信息
                Object[] updateColumns = new Object[]{
                        store.getCompanyId(), store.getStoreType(), store.getStoreCode(), store.getStoreName(), store.getStoreFullName(),
                        store.getMobile(), store.getContactor(), store.getTel(), store.getStoreAddress(), store.getStatus(),
                        store.getUpdateTime(), store.getRemark(), store.getUpdateTime(), store.getStoreId()
                };
                //存在更新
                Integer count = MysqlJDBCUtil.execUpdate(sql, connection, updateColumns);
                updateCount += count;
                if (count == 0) {
                    needInsert = true;
                    // 插入信息
                    insertValues.append(changeValue(store.getStoreId()))
                            .append(changeValue(store.getCompanyId()))
                            .append(changeValue(store.getStoreCode()))
                            .append(changeValue(store.getStoreType()))
                            .append(changeValue(store.getStoreName()))
                            .append(changeValue(store.getStoreFullName()))
                            .append(changeValue(store.getContactor()))
                            .append(changeValue(store.getTel()))
                            .append(changeValue(store.getMobile()))
                            .append(changeValue(store.getProvinceName()))
                            .append(changeValue(store.getCityName()))
                            .append(changeValue(store.getZoneName()))
                            .append(changeValue(store.getStoreAddress()))
                            .append(changeValue(store.getStatus()))
                            .append(changeValue(store.getCreateTime()))
                            .append(changeValue(store.getUpdateTime()))
                            .append(changeValue(store.getRemark()))
                            .deleteCharAt(insertValues.length() - 2)
                            .append("), (");
                }
            }
            if (needInsert) {
                //不存在插入
                sql = "INSERT INTO sys_store (store_id, company_id, store_code, store_type, store_name, store_full_name, contactor, tel, mobile, province_name, city_name, zone_name, store_address, status, create_time, update_time, remark, transport_time) VALUES ({STORE_VALUES}) ;";
                sql = sql.replace("{STORE_VALUES}", insertValues.substring(0, insertValues.length() - 4));

                insertCount = MysqlJDBCUtil.execUpdate(sql, connection);
            }
            MysqlJDBCUtil.commit(connection);
        } catch (Exception e) {
            e.printStackTrace();
            MysqlJDBCUtil.rollback(connection);
        } finally {
            MysqlJDBCUtil.close(connection);
        }
    }

    public Object changeValue(Object value) {
        if (value instanceof Date) {
            value = DateUtil.format((Date) value, B2BTimeConstant.DEFAULT_TIME_FORMAT.getFormat());
        }
        return MyStrUtil.isEmpty(value) ? null + ", " : "'" + value + "', ";
    }

    @Override
    public void convertInspectionOrderData() {

    }

    @Override
    public void storeDataTransport() {
        // do nothing
    }

    @Override
    public void productDataTransport() {
        // do nothing
    }

    @Override
    public void outOrderDataTransport() {
        // do nothing
    }

    @Override
    public void uploadMemberData() {

    }

    @Override
    public void uploadSaleData() {

    }

    @Override
    public void uploadStockData() {

    }
}
